package com.example.shushiyunsst.fragment.main.transaction.child.kline_chart.k_line_chart_portrait_content

import android.annotation.SuppressLint
import android.os.Bundle
import android.util.Log
import android.view.View
import android.widget.ImageView
import android.widget.TextView
import android.widget.Toast
import androidx.lifecycle.lifecycleScope
import com.alibaba.fastjson.JSON
import com.alibaba.fastjson.parser.Feature
import com.example.library_common.album.utils.Utils
import com.example.library_common.base.BaseFragmentEx
import com.example.library_common.networking.RestClient
import com.example.library_common.utils.even.MessageWrap
import com.example.shushiyunsst.MyApp
import com.example.shushiyunsst.R
import com.example.shushiyunsst.fragment.main.transaction.child.TRANSFER_INDEX_DATA_REFRESH
import com.example.shushiyunsst.fragment.main.transaction.child.kline_chart.KlineChartInterface
import com.example.shushiyunsst.fragment.main.transaction.child.kline_chart.KlineLandscapeFragment
import com.example.shushiyunsst.util.flutter_bridgt.EventChannelManager
import com.example.shushiyunsst.util.flutter_bridgt.FLUTTER_TO_NATIVE
import io.flutter.embedding.android.FlutterFragment
import io.flutter.embedding.android.RenderMode
import io.flutter.embedding.engine.FlutterEngineCache
import io.flutter.plugin.common.EventChannel
import io.flutter.plugin.common.MethodCall
import io.flutter.plugin.common.MethodChannel
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import org.json.JSONObject


class KLineChartPanelFragment : BaseFragmentEx(), View.OnClickListener {
    companion object {
        fun newInstance(): KLineChartPanelFragment {
            val args = Bundle()
            val fragment = KLineChartPanelFragment()
            fragment.arguments = args
            return fragment
        }
    }

    private var transactionUIInvokeListener: KlineChartInterface? = null

    fun setTransactionUIInvokeListener(listener: KlineChartInterface?) {
        this.transactionUIInvokeListener = listener
    }

    private lateinit var priceHeaderTv: TextView
    private lateinit var upDown: TextView
    private lateinit var txNumsIn24Hour: TextView
    private lateinit var maxPrice: TextView
    private lateinit var minPrice: TextView

    private lateinit var durationLayout: View
    private lateinit var durationTv: TextView
    private lateinit var durationIcon: ImageView

    private lateinit var standardLayout: View
    private lateinit var standardTv: TextView
    private lateinit var standardIcon: ImageView

    private lateinit var flutterFragment: FlutterFragment

    private lateinit var screenBtn: ImageView

    private val eventChannel =
        EventChannelManager.instance?.getEventChannel(MyApp.KLINE_CHART_PANEL)

//    private var eventChannelPlugin: EventChannelPlugin? = null

    private var mMethodChannel: MethodChannel? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        mSuperBackPressedSupport = false
    }

    override fun getLayoutId(): Any {
        return R.layout.k_line_chart_panel_fragment
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        priceHeaderTv = view.findViewById(R.id.priceHeaderTv)
        upDown = view.findViewById(R.id.upDown)
        txNumsIn24Hour = view.findViewById(R.id.txNumsIn24Hour)
        maxPrice = view.findViewById(R.id.maxPrice)
        minPrice = view.findViewById(R.id.minPrice)

        durationLayout = view.findViewById(R.id.durationLayout)
        durationTv = view.findViewById(R.id.durationTv)
        durationIcon = view.findViewById(R.id.durationIcon)

        standardLayout = view.findViewById(R.id.standardLayout)
        standardTv = view.findViewById(R.id.standardTv)
        standardIcon = view.findViewById(R.id.standardIcon)
        screenBtn = view.findViewById(R.id.screenBtn)

        durationLayout.setOnClickListener(this)
        standardLayout.setOnClickListener(this)
        screenBtn.setOnClickListener(this)
    }

    override fun onLazyInitView(savedInstanceState: Bundle?) {
        super.onLazyInitView(savedInstanceState)


        if (savedInstanceState == null) {

            flutterFragment = FlutterFragment.withCachedEngine(MyApp.KLINE_CHART_PANEL)
                .renderMode(RenderMode.texture)
                .build<FlutterFragment>()
            val mFlutterEngine = FlutterEngineCache.getInstance().get(MyApp.KLINE_CHART_PANEL)

            mMethodChannel = MethodChannel(mFlutterEngine?.dartExecutor, FLUTTER_TO_NATIVE)

            mMethodChannel?.setMethodCallHandler(methodCallHandler)

            childFragmentManager.beginTransaction()
                .add(R.id.WalletView, flutterFragment)
                .commitAllowingStateLoss()

            loadData()

        }

    }

    private val  methodCallHandler: MethodChannel.MethodCallHandler=
        MethodChannel.MethodCallHandler {
                call, result ->

            when(call.method){
                "screen_option_land"->{
//                    Toast.makeText(_mActivity,"screen_option",Toast.LENGTH_SHORT).show()
                    val shareUrl = call.argument<String>("shareUrl")?:""
                    Log.v("shareUrl=", shareUrl)
                    result.success("处理完成")
                    start(KlineLandscapeFragment.newInstance())
                }
                "requireNativeData"->{
                    val param = call.argument<String>("param")?:""
//                    Toast.makeText(_mActivity,param,Toast.LENGTH_SHORT).show()
                    Log.v("requireNativeData=", param)
                    result.success("处理完成")
                    rootView.postDelayed({
                        requireKLineData(param)
                    },1000)
                }
                else->{
                    result.notImplemented()
                }
            }
        }

    private fun requireKLineData(param:String) {
        val obj =  JSONObject(param)
        val ktype = obj["title"].toString()
        val map = mapOf(
            "ktype" to ktype
        )
        RestClient.builder()
            .raw(JSON.toJSONString(map))
             .url(R.string.queryKLineData)
             .success {
                 Log.d("requireKLineData", "requireKLineData: $it")
                 eventChannel?.send(it)
             }
            .failure {
                eventChannel?.send("[]")
            }
            .error { _, _ ->
                eventChannel?.send("[]")
            }
            .build().post()
    }

    private fun loadData() {
//        lifecycleScope.launch {
//            val data = withContext(Dispatchers.IO) {
//                Utils.getJsonFromRaw(_mActivity, R.raw.chart_kline)
//            }
//            val eventChannel =
//                EventChannelManager.instance?.getEventChannel(MyApp.KLINE_CHART_PANEL)
//            eventChannel?.send(data)
//
//        }

//        var chart_kline = Utils.getJsonFromRaw(_mActivity, R.raw.chart_kline)
    }


    private fun netRequest() {
        val transIndexNode = transactionUIInvokeListener?.getTransIndexNode()
        val tokenName = transIndexNode?.iconType?.tokenName ?: ""
        val map = mapOf(
            "tokenType" to tokenName
        )
        RestClient.builder()
            .raw(JSON.toJSONString(map))
            .url(R.string.queryTokenBaseInfo)
            .success {
                parseQueryTokenBaseInfo(it)
            }
            .build()
            .post()
    }

    override fun handMessage(msg: MessageWrap?) {
        super.handMessage(msg)
        when (msg?.message) {
            TRANSFER_INDEX_DATA_REFRESH -> {
                netRequest()
            }
        }
    }

    @SuppressLint("SetTextI18n")
    private fun parseQueryTokenBaseInfo(it: String?) {
        val obj = JSON.parseObject(it)

        val price = obj["price"].toString()
        priceHeaderTv.text = price

        val maxPriceStr = obj["maxPrice"].toString()
        maxPrice.text = "高: $maxPriceStr"

        val minPriceStr = obj["minPrice"].toString()
        minPrice.text = "低: $minPriceStr"

        val txNumsIn24HourStr = obj["txNumsIn24Hour"].toString()
        txNumsIn24Hour.text = "24H: $txNumsIn24HourStr"

        val upDownStr = obj["updown"].toString()
        upDown.text = "涨跌: $upDownStr"
    }

    override fun onClick(v: View?) {
        when (v?.id) {
            R.id.durationLayout -> {

            }
            R.id.standardLayout -> {

            }
//            R.id.screenBtn -> {
//
//                eventChannelPlugin?.send("android hello")
//
//            }
        }
    }
}